<?php

namespace app\admin\controller;

use app\comm\func\CommFunc;
use app\comm\func\Office;
use think\Controller;
use think\Request;
use think\Db;
use think\Session;
use app\comm\func\Consts;

/**
 * Class Student 学生模块
 * @package app\admin\controller
 */
class Student extends Controller
{
    /**
     * @param Request $request 学生列表
     * @return mixed
     */
    public function StudentList(Request $request)
    {
        if ($request->isPost()) {
            CommFunc::emptyVerify($request->post(), ['name']);
            CommFunc::conditionAdd($condition, $request->post(), ['name']);
            $student = Db::table('student')
                ->where('student_name', 'like', '%' . $condition['name'] . '%')
                ->paginate(5, true);
            $this->SeachStudent($student);
            return $this->fetch();
        } else {
            $role_id = Session::get('auth')['role_id'];
            if ($role_id == 1) {
                $student = Db::table('student')->paginate(5, true);
                $this->SeachStudent($student);
                return $this->fetch();
            } else {
                $teacher_id = Session::get('auth')['aid'];  //获取到了老师的id teacher_class表老师最大的id那条记录就是该老师当前带的班级
                $teacherClassMaxId = Db::table('teacher_class')
                    ->where('teacher_id', $teacher_id)->max('id');
                $classroom = Db::table('teacher_class')
                    ->where('id', $teacherClassMaxId)->find(); //获取登录老师教的班级阶段
                $studentAll = Db::table('student')
                    ->where('classroom', $classroom['classroom_id'])
                    ->where('teacher', $classroom['teacher_id'])->select();
                foreach ($studentAll as $key => $vo) {
                    $studentAll[$key]['classroom'] = Db::table('classroom')
                        ->where('cid', $vo['classroom'])->find();
                    $studentAll[$key]['teacher'] = Db::table('admin')
                        ->where('aid', $studentAll[$key]['classroom']['teacher_id'])->find();
                }
                $this->assign('student', $studentAll);
                return $this->fetch();
            }
        }
    }

    /**
     * 合并学生查询
     * @param array $student
     * @return mixed
     */
    public function SeachStudent($student = [])
    {
        $studentAll = $student->all();
        $page = $student->render();
        foreach ($studentAll as $key => $vo) {
            $studentAll[$key]['classroom'] = Db::table('classroom')
                ->where('cid', $vo['classroom'])->find();
            $studentAll[$key]['teacher'] = Db::table('admin')
                ->where('aid', $studentAll[$key]['classroom']['teacher_id'])->find();
        }
        $this->assign(['student' => $studentAll, 'page' => $page]);
        return $studentAll;
    }

    /**
     * @param Request $request 学生列表详情
     * @return mixed
     */
    public function details(Request $request)
    {
        CommFunc::emptyVerify($request->get(), ['id']);
        CommFunc::conditionAdd($condition, $request->get(), ['id']);
        $data = Db::table('student')->where('id', $condition['id'])->find();
        $data['label'] = json_decode($data['label'], true);
        foreach ($data['label'] as $key => $vo) {
            $data['label'][$key] = Db::table('system')
                ->where('id', $vo)->field('option')->find();
        }
        $res = Db::table('student_class')
            ->where('student_id', $condition['id'])->order('id')->select();
        if (!empty($res) || count($res) >= 2) {
            $studentDownCount = count($res) - 1;
            foreach ($res as $key => $vo) {
                $result[$key]['classroom'] = Db::table('classroom')
                    ->where('cid', $vo['classroom_id'])->find();
                $result[$key]['teacher'] = Db::table('admin')
                    ->where('aid', $result[$key]['classroom']['teacher_id'])->find();
            }
            $result = array_splice($result, 1);
            $this->assign([
                'studentDownCount' => $studentDownCount,
                'result' => $result,
                'student' => $data
            ]);
        } else {
            $this->assign([
                'studentDownCount' => 0,
                'student' => $data
            ]);
        }
        return $this->fetch();
    }

    /**
     * @param Request $request 学生添加
     * @return mixed
     */
    public function StudentAdd(Request $request)
    {
        if ($request->isPost()) {
            CommFunc::emptyVerify($request->post(), Consts::$studentAdd);
            CommFunc::conditionAdd($condition, $request->post(), Consts::$studentAdd);
            Db::startTrans();
            $classroom_id = $condition['classroom'];
            $condition['status'] = 1;
            $condition['label'] = '["1"]';
            $classroom = Db::table('classroom')->where('cid', $condition['classroom'])->find();
            $condition['teacher'] = $classroom['teacher_id'];
            $insertId = Db::table('student')->insertGetId($condition);
            if ($insertId > 0) {
                $new = [];
                $new['student_id'] = $insertId;
                $new['classroom_id'] = $classroom_id;
                $res = Db::table('student_class')->insert($new);
                if ($res > 0) {
                    $score = [];
                    $score['student_id'] = $insertId;
                    $arr = Consts::$sroce;
                    $score['examination'] = json_encode($arr);
                    $score['classroom'] = $classroom_id;
                    $score['stage'] = 1;
                    $scoreType = DB::table('score')->insert($score);
                    if ($scoreType > 0) {
                        $everyDay = [];
                        $everyDay['student_id'] = $insertId;
                        $everyDay['time'] = time();
                        $everyDay['option'] = '';
                        $everyDay['classroom'] = $classroom_id;
                        $everyDay['stage'] = 1;
                        $everyDayType = Db::table('everyday')->insert($everyDay);
                        if ($everyDayType > 0) {
                            Db::commit();
                            CommFunc::ajaxReturn(Consts::$successful);
                        } else {
                            CommFunc::is_RollBack();
                        }
                    } else {
                        CommFunc::is_RollBack();
                    }
                } else {
                    CommFunc::is_RollBack();
                }
            } else {
                CommFunc::is_RollBack();
            }
        } else {
            $classroom = Db::table('classroom')
                ->where('stage', 1)
                ->where('status', 1)->select();
            $this->assign('classroom', $classroom);
            return $this->fetch();
        }
    }

    /**
     * @param Request $request 学生信息修改
     * @return mixed
     */
    public function StudentEdit(Request $request)
    {
        if ($request->isPost()) {
            CommFunc::emptyVerify($request->post(), Consts::$studentEdit);
            CommFunc::conditionAdd($condition, $request->post(), Consts::$studentEdit);
            $condition['label'] = json_encode($condition['label']);
            $id = $condition['id'];
            unset($condition['id']);
            $updateType = Db::table('student')->where('id', $id)->update($condition);
            if ($updateType > 0) {
                CommFunc::ajaxReturn(Consts::$successful);
            } else {
                CommFunc::ajaxReturn(Consts::$failure);
            }
        } else {
            CommFunc::emptyVerify($request->param(), ['id']);
            CommFunc::conditionAdd($condition, $request->param(), ['id']);
            $res = Db::table('student')
                ->where('id', $condition['id'])->find();
            $status = Db::table('system')
                ->where('type', 1)->select();
            $label = Db::table('system')
                ->where('type', 2)->select();
            $this->assign(['student' => $res, 'status' => $status, 'label' => $label]);
            return $this->fetch();
        }
    }

    /**
     * @param Request $request 留级按钮
     */
    public function StudentDown(Request $request)
    {
        CommFunc::emptyVerify($request->post(), ['id']);
        CommFunc::conditionAdd($condition, $request->post(), ['id']);  //获取学生id
        $student = Db::table('student')->where('id', $condition['id'])->find(); //根据学生id查这个学生
        $classroom = Db::table('classroom')->where('cid', $student['classroom'])->find(); //根据学生表的班级号查这个班级的阶段
        $stage = $classroom['stage']; //目前该学生对应班级的阶段
        if ($stage - 3 >= 1 || $stage - 2 >= 1 || $stage - 1 >= 1 || $stage - 1 == 0) {
            CommFunc::ajaxReturn(Consts::$successful);
        } else {
            CommFunc::ajaxReturn(Consts::$failure);
        }
    }

    /**
     * @param Request $request 留级之后选择班级
     * @return mixed
     */
    public function ChooseClassroom(Request $request)
    {
        if ($request->isPost()) {
            CommFunc::emptyVerify($request->post(), ['id', 'classroom_id']);
            CommFunc::conditionAdd($condition, $request->post(), ['id', 'classroom_id']);
            Db::startTrans();
            $condition['student_id'] = $condition['id'];
            unset($condition['id']);
            $insertId = Db::table('student_class')->insertGetId($condition);
            if ($insertId > 0) {
                $classroom = DB::table('classroom')->where('cid', $condition['classroom_id'])->find();
                $updateType = Db::table('student')->where('id', $condition['student_id'])
                    ->data([
                        'status' => 3,
                        'teacher' => $classroom['teacher_id'],
                        'classroom' => $condition['classroom_id']
                    ])->update();
                if ($updateType > 0) {
                    $score['student_id'] = $condition['student_id'];
                    $score['examination'] = json_encode(Consts::$sroce);
                    $score['classroom'] = $condition['classroom_id'];
                    $score['stage'] = $classroom['stage'];
                    $scoreInsertType = Db::table('score')->insert($score);
                    if ($scoreInsertType > 0) {
                        $every['student_id'] = $condition['student_id'];
                        $every['option'] = '';
                        $every['time'] = time();
                        $every['classroom'] = $condition['classroom_id'];
                        $every['stage'] = $classroom['stage'];
                        $everyInserType = Db::table('everyday')->insert($every);
                        if ($everyInserType > 0) {
                            Db::commit();
                            CommFunc::ajaxReturn(Consts::$successful);
                        } else {
                            CommFunc::is_RollBack();
                        }
                    } else {
                        CommFunc::is_RollBack();
                    }
                } else {
                    CommFunc::is_RollBack();
                }
            } else {
                CommFunc::is_RollBack();
            }
        } else {
            CommFunc::emptyVerify($request->param(), ['id']);
            CommFunc::conditionAdd($condition, $request->param(), ['id']);
            $student = Db::table('student')
                ->where('id', $condition['id'])->find();
            $classroom = Db::table('classroom')
                ->where('cid', $student['classroom'])->find();
            $res['id'] = $condition['id'];
            $res['classroom'] = Db::table('classroom')
                ->where('cid', '<>', $classroom['cid'])
                ->where('stage', '<=', $classroom['stage'])->select();
            $this->assign('res', $res);
            return $this->fetch();
        }
    }

    /**
     * @param Request $request 学生删除
     */
    public function StudentDel(Request $request)
    {
        CommFunc::emptyVerify($request->post(), ['id']);
        CommFunc::conditionAdd($condition, $request->post(), ['id']);
        Db::startTrans();
        $deleteType = Db::table('student')
            ->where('id', $condition['id'])->where('status', 3)->delete();
        if ($deleteType) {
            $student_classType = Db::table('student_class')
                ->where('student_id', $condition['id'])->delete();
            if ($student_classType) {
                Db::commit();
                CommFunc::ajaxReturn(Consts::$successful);
            } else {
                CommFunc::is_RollBack();
            }
        } else {
            CommFunc::is_RollBack();
        }
    }

    /**
     * @return string 下载学生表
     */
    public function StudentExcelDown()
    {
        $auth = Session::get('auth');
        if ($auth['role_id'] == 1) {
            $orders = Db::table('student')
                ->field('status,label,classroom,teacher', true)
                ->select();
        } else {
            $teacher_id = Session::get('auth')['aid'];  //获取到了老师的id teacher_class表老师最大的id那条记录就是该老师当前带的班级
            $teacherClassMaxId = Db::table('teacher_class')
                ->where('teacher_id', $teacher_id)->max('id');
            $classroom = Db::table('teacher_class')
                ->where('id', $teacherClassMaxId)->find(); //获取登录老师教的班级阶段
            $orders = Db::table('student')
                ->where('classroom', $classroom['classroom_id'])
                ->where('teacher', $classroom['teacher_id'])
                ->field('status,label,classroom,teacher', true)
                ->select();
        }
        $excels = new Office();
        $head = Consts::$head;
        $keys = Consts::$keys;
        $excels->outdata('学生表下载记录', $orders, $head, $keys);
    }

}